package org.corey.share.business;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;
import org.corey.share.db.entity.CoreyFile;
import org.corey.share.misc.Common;
import org.corey.share.misc.Constants;

import com.google.appengine.api.datastore.Blob;

public class FileUploadEntryPoint extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public FileUploadEntryPoint() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletFileUpload upload = new ServletFileUpload();
		try {
			FileItemIterator iter;
			List<CoreyFile> coreyFiles = new ArrayList<CoreyFile>();
			iter = upload.getItemIterator(request);
			FileUploadAction action = new FileUploadAction();
			while (iter.hasNext()) {
				FileItemStream item = iter.next();
				InputStream stream = item.openStream();
				String itemName=item.getFieldName();
				if (!item.isFormField()) {
					CoreyFile file = new CoreyFile();
					String contentType = item.getContentType();
					String fileName = Common.getFileNameFromFilePath(item.getName());
					if(!Common.isEmpty(contentType) &&!Common.isEmpty(fileName)){
						Blob content = new Blob(IOUtils.toByteArray(stream));
						file.setContentType(contentType);
						file.setContent(content);
						file.setFileName(fileName);
						coreyFiles.add(file);
					}
				}else{
					String value=Streams.asString(stream, "UTF-8");
					if("respository".endsWith(itemName)){
						action.setRespository(value);
					}
				}
			}
			HttpSession session=request.getSession();
			Long user=Common.parseLong(session.getAttribute(Constants.USER_KEY));
			if(user==null){
				user=148275L;
			}
			action.setUser(user);
			action.setFiles(coreyFiles);
			String filesInfo = action.execute();
			request.setAttribute("filesInfo", filesInfo);
		} catch (FileUploadException e) {
			request.getRequestDispatcher("/error.jsp").forward(request,
					response);
		}
		request.getRequestDispatcher(request.getContextPath()+"/admin/admin_attachements_upload.jsp").forward(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
